package edu.ccut.saturn.studio.logic;

import java.util.Iterator;
import java.util.List;

import org.w3c.dom.Document;
import org.w3c.dom.Node;

import edu.ccut.saturn.studio.core.util.xml.SaturnW3CUtil;
import edu.ccut.saturn.studio.logic.model.Shape;
import edu.ccut.saturn.studio.logic.model.saturn.SaturnParameter;
import edu.ccut.saturn.studio.logic.model.xml.loader.ComponentNodeLoader;
import edu.ccut.saturn.studio.logic.model.xml.loader.InformationNodeLoader;
import edu.ccut.saturn.studio.logic.model.xml.loader.logic.StartNodeInLogicLoader;
import edu.ccut.saturn.studio.util.ConversionUtil;

public class NodeChooseFactory {
	private static final String SATURN_PARAMETER_KEY = "${context}";

	/**
	 * 根据不同的搜索KEY，返回SHAPE
	 * 
	 * @param arg
	 * @param doc
	 * @return
	 */
	public static Shape getInstance(String arg, Document doc) {
		String expressions[] = arg.split("--");
		String key = new String();
		if (expressions[0].endsWith(".component")) {
			ComponentNodeLoader componentLoader = new ComponentNodeLoader();
			List<Shape> components = componentLoader.loadNodes(doc
					.getDocumentElement());
			if (components != null && components.size() != 0) {
				Shape shape = components.get(0);
//				shape.setName(ModelXmlUtils.componentDocumentNameValue(doc));
				Node root = doc.getDocumentElement();
				Node componentNode = SaturnW3CUtil.getFirstChildByName(root, "component");
				shape.setName(SaturnW3CUtil.getNodeAttributeValue(componentNode, "name"));
				ConversionUtil.scopeMap(shape.getParameters());
				return shape;
			}
		} else if (expressions[0].endsWith(LogicWizardPage.FILE_TYPE)) {
			StartNodeInLogicLoader logicLoader = new StartNodeInLogicLoader();
			InformationNodeLoader inforLoader = new InformationNodeLoader();
			List<Shape> logics = logicLoader
					.loadNodes(doc.getDocumentElement());
			List<Shape> infoList = inforLoader.loadNodes(doc
					.getDocumentElement());
			if (logics != null
					&& (logics.size() != 0 && infoList != null && infoList
							.size() != 0)) {
				Shape shape = logics.get(0);
				List<SaturnParameter> parameters = shape.getParameters();
				ConversionUtil.scopeMap(parameters);
				Iterator<SaturnParameter> iterator = parameters.iterator();
				while (iterator.hasNext()) {
					SaturnParameter parameter = iterator.next();
					if (parameter.getValueKey().equals(SATURN_PARAMETER_KEY)) {
						iterator.remove();
					}
				}
				for (int i = 0; i < parameters.size(); i++) {
					parameters.get(i).setId(String.valueOf(i));
				}

				Shape info = infoList.get(0);
				shape.setName(info.getName());
				shape.setDescription(info.getDescription());
				return shape;
			}
		}
		
		return null;
	}
}
